import Solflare from '@solflare-wallet/sdk';
import { PublicKey, Transaction } from '@solana/web3.js'; // 导入 PublicKey 和 Transaction 类型

// 定义 WalletProvider 接口
interface WalletProvider {
  publicKey: PublicKey | null;
  connect: () => Promise<void>;
  disconnect: () => Promise<void>;
  signTransaction: (transaction: Transaction) => Promise<Transaction>;
  signAllTransactions?: (transactions: Transaction[]) => Promise<Transaction[]>;
  signMessage?: (msg: Uint8Array) => Promise<Uint8Array>;
}

// 处理 Solana 钱包类型
interface SolanaWindow extends Window {
  solana?: WalletProvider;
}

declare const window: SolanaWindow;

interface Wallet {
  publicKey: PublicKey | null;
  connected: boolean;
  currentWallet: string;
  xWallet: WalletProvider | null;

  setCurrentWallet: (walletName: string) => void;
  connect: () => Promise<void>;
  disconnect: () => Promise<void>;
  signTransaction: (transaction: Transaction) => Promise<Transaction | null>;
  signAllTransactions?: (transactions: Transaction[]) => Promise<Transaction[] | null>;
  signMessage?: (msg: Uint8Array) => Promise<Uint8Array | null>;
}

let wallet: Wallet = {
  publicKey: null,
  connected: false,
  currentWallet: 'solflare',
  xWallet: null,

  // 设置当前钱包
  setCurrentWallet(walletName: string) {
    this.currentWallet = walletName;
    this.xWallet = null;
    this.connected = false;
    this.publicKey = null;
  },

  // 连接钱包
  async connect(): Promise<void> {
    try {
      if (this.currentWallet === 'solflare') {
        const solflare = new Solflare();
        await solflare.connect();
        if (solflare.publicKey) {  // 检查 publicKey 而不是 isConnected
          this.xWallet = {
            publicKey: solflare.publicKey,
            connect: solflare.connect.bind(solflare),
            disconnect: solflare.disconnect.bind(solflare),
            signTransaction: async (tx: Transaction) => {
              const signedTx = await solflare.signTransaction(tx);
              return signedTx as Transaction; // 处理类型转换
            },
            signAllTransactions: async (txs: Transaction[]) => {
              const signedTxs = await solflare.signAllTransactions(txs);
              return signedTxs as Transaction[];
            },
            signMessage: solflare.signMessage.bind(solflare)
          };
          this.connected = true;
          this.publicKey = solflare.publicKey;
        }
      } else if (this.currentWallet === 'solana') {
        const solana = window.solana;
        if (solana) {
          await solana.connect();
          if (solana.publicKey) {
            this.connected = true;
            this.xWallet = solana;
            this.publicKey = solana.publicKey;
          }
        }
      }
    } catch (error) {
      console.error('connect wallet:', error);
    }
  },

  // 断开连接
  async disconnect(): Promise<void> {
    if (this.xWallet) {
      await this.xWallet.disconnect();
    }
    this.xWallet = null;
    this.connected = false;
    this.publicKey = null;
  },

  // 签名交易
  async signTransaction(transaction: Transaction): Promise<Transaction | null> {
    if (this.xWallet) {
      return await this.xWallet.signTransaction(transaction);
    }
    return null;
  },

  // 签名所有交易
  async signAllTransactions(transactions: Transaction[]): Promise<Transaction[] | null> {
    if (this.xWallet && this.xWallet.signAllTransactions) {
      return await this.xWallet.signAllTransactions(transactions);
    }
    return null;
  },

  // 签名消息
  async signMessage(msg: Uint8Array): Promise<Uint8Array | null> {
    if (this.xWallet && this.xWallet.signMessage) {
      return await this.xWallet.signMessage(msg);
    }
    return null;
  }
};

export default wallet;
